<?php
namespace Mobile\Controller;
use Think\Controller;
use Mobile\Controller\SellerController;

class AlipayController extends Controller{
   
    private $seller;
    
    public function _initialize(){
        $this->seller = new SellerController();
    }

    public function createSign(){
        Vendor('Alipay.notify');
        $notify = new \Notify();
        $sign = $notify->createSign();
        if(!empty($sign)){
            
            $this->ajaxReturn(array(
                'code' => 1,
                'msg'  => '成功',
                'data' => $sign,
            ));
        }
        $this->ajaxReturn(array(
            'code' => 0,
            'msg'  => '失败',
        ));
    }
    
    public function verify(){
        Vendor('Alipay.notify');
        $notify = new \Notify();
        $notify->verify();
    }

    public function notify(){

        Vendor('Alipay.notify');
        $notify = new \Notify();
        $verify_result = $notify->execute();
        if($verify_result) {//验证成功
	
            //商户订单号,前15位是随机数，第16位是交易类型（申请肖像权or邀请体验），后面的是本地记录（邀请体验记录或申请肖像权id）id
            $out_trade_no = $_POST['out_trade_no'];
            //支付宝交易号
            $alipay_trade_no = $_POST['trade_no'];
            //支付金额
            $total_fee = $_POST['total_fee'];
            //商品名称
            $subject = $_POST['subject'];
            //卖家账号
            $seller_email = $_POST['seller_email'];
            //买家账号
            $buyer_email = $_POST['buyer_email'];
            //交易创建时间
            $gmt_create_time = $_POST['gmt_create'];
            //交易付款时间
            $gmt_payment_time = $_POST['gmt_payment'];
            //商品描述
            $pay_body = $_POST['body'];
            
            //日志文件
            logResult('请求地址：' . $_SERVER['REQUEST_URI']);
            $str = '交易完成 : 商户订单号： ' .$out_trade_no. 
                    ' 支付宝订单号： ' .$alipay_trade_no. ' 商品名称： ' . $subject . 
                    ' 交易金额： ' . $total_fee . ' 卖家账号：' . $seller_email . 
                    '买家账号： ' . $buyer_email . '交易创建时间：' . $gmt_create_time .
                    '交易付款时间：' . $gmt_payment_time . '商品描述：' . $pay_body . '交易类型：'. $_POST['pay_type'];
            logResult($str);
            
            //交易记录内容
            $trade_type = substr($out_trade_no, 15, 1);
            $trade_no   = substr($out_trade_no, 16);
            $trade_record = array(
                'local_trade_no'    => $out_trade_no,
                'alipay_trade_no'   => $alipay_trade_no,
                'subject'           => $subject,
                'total_fee'         => $total_fee,
                'seller_email'      => $seller_email,
                'buyer_email'       => $buyer_email,
                'create_time'       => strtotime($gmt_create_time),
                'pay_time'          => strtotime($gmt_payment_time),
                'pay_body'          => $pay_body,   
                'type'              => 0,           //打款到平台还是提现，默认0打款到平台，1提现
                'trade_type'        => $trade_type, //交易类型（暂定）0-申请肖像权，1-模特为邀请体验付押金，2-卖家付邀请体验费用
                'trade_no'          => $trade_no,   //本地订单号，根据trade_type分成两种订单，申请肖像权记录id和邀请体验记录id
                'trade_status'      => 0,           //待付款状态
            );
            
            //根据支付状态生成交易记录
            if($_POST['trade_status'] == 'TRADE_FINISHED') {
                //支付最终完成状态（未开通高级支付的支付完成状态，开通高级支付过了签约的可退款日期）
                $is_order_exist = M('Order')->where(array('alipay_trade_no' => $alipay_trade_no, 'local_trade_no' => $out_trade_no, 'trade_status' => 1))->find();
                if(! $is_order_exist){
                    M('Order')->add($trade_record);
                }
            } else if ($_POST['trade_status'] == 'TRADE_SUCCESS') { 
                //高级支付支付成功状态
                    M('Order')->where(array('alipay_trade_no' => $alipay_trade_no, 'local_trade_no' => $out_trade_no))->save(array('trade_status' => 1));
                    if($trade_type % 2 == 0){   //卖家支付肖像权和邀请体验费
                        $model = $this->changeMessageStatus($trade_type, $trade_no);
                    }elseif($trade_type == 1){  //模特支付邀请体验押金
                        $this->modelPayCash($trade_no);
                    }
                    $this->addModelcoinRecord($trade_type, $trade_no, $model['money'], $model['id']);
            } else if ($_POST['trade_status'] == 'WAIT_BUYER_PAY'){
                //交易创建待付款状态
                $is_order_exist = M('Order')->where(array('alipay_trade_no' => $alipay_trade_no, 'local_trade_no' => $out_trade_no))->find();
                if(! $is_order_exist){
                    M('Order')->add($trade_record);
                }
            }
            echo "success";		//请不要修改或删除
        } else {
            //验证失败
            echo "fail";
            //调试用，写文本函数记录程序运行情况是否正常
        }
    }
    
    public function modelPayCash($trade_no) {
        $record = M('Invite_experience')->find($trade_no);
        if($record['return_type'] == 0){
            M('Invite_experience')->save(array('id' => $trade_no, 'ensure_moeny_paid' => 1));
        }
    }

    /**
     *  支付成功后根据支付的类型（申请肖像权还是邀请体验）来更改对应记录的状态
     *  @param int $type 支付的交易类型：0申请肖像权，1邀请体验模特交押金，2邀请体验卖家付款
     */
    public function changeMessageStatus($type, $id){
        $table = $type==0 ? 'Apply_portrait' : 'Invite_experience';
        if($type == 0){
            $model = M('Apply_portrait');
            $status = 5;
            $msg = '卖家已将申请肖像权费用托管到平台';
        }elseif($type == 2){
            $model = M('Invite_experience');
            $status = 5; 
            $msg = '卖家已将邀请体验费用托管到平台';
        }
        if(isset($model)){
            $model->save(array('id' => $id, 'status' => $status));
            $record = $model->where(array('id' => $id))->find();
            if($type == 0){
                $money = $record['total_money'];
            }else{
                $money = $record['total_fee'];
            }
            $this->seller->sendMsg($record['mid'], $type+1, $msg);
            return array(
                'money' => $money,
                'id'    => $record['id'],
            );
        }
    }
    
    /**
     * 添加麻豆币记录（麻豆币暂时与人民币比例1:1）
     * @param type $trade_type  交易类型：0-卖家申请肖像权；1-模特支付邀请码押金；2-卖家支付邀请体验
     * @param type $trade_id    交易记录（申请肖像权记录/邀请体验记录）id
     * @param type $order_id    订单id
     * @param type $total_fee   交易金额
     * @param type $uid         当前只包括模特id
     */
    public function addModelcoinRecord($trade_type, $trade_id, $total_fee, $uid){
        $income_percent = C('income_percent');
        switch ($trade_type){
            case 0:
                $remark = '卖家申请肖像权';
                $model_income = $income_percent * $total_fee;   //模特收益
                $type = 0;
                break;
            case 1:
                $remark = '模特支付邀请体验的押金';
                $model_income = $total_fee;
                $type = 1;
                break;
            case 2:
                $remark = '卖家支付邀请体验';
                $model_income = $income_percent * $total_fee;
                $type = 1;
                break;
        }
        $platform_income = $total_fee - $model_income;      //平台收益
        $model_coin = M('Model_coin');
        //模特麻豆币添加
        $last_model_record = $model_coin->where(array('uid' => $uid))->order(array('id' => 'desc'))->find();
        if(!empty($last_model_record)){
            $model_data = array(
                'uid'               => $uid,
                'user_type'         => 0,
                'trade_type'        => $type,
                'trade_id'          => $trade_id,
                'trust_coin'        => $last_model_record['trust_coin'] + $model_income,
                'available_coin'    => $last_model_record['available_coin'],
                'current_trade_coin'=> $model_income,
                'after_trade_coin'  => $last_model_record['after_trade_coin'] + $model_income,
                'type'              => 0,
                'remark'            => $remark,
                'status'            => 1,
            );
        }else{
            $model_data = array(
                'uid'               => $uid,
                'user_type'         => 0,
                'trade_type'        => $type,
                'trade_id'          => $trade_id,
                'trust_coin'        => $model_income,
                'available_coin'    => 0,
                'current_trade_coin'=> $model_income,
                'after_trade_coin'  => $model_income,
                'type'              => 0,
                'remark'            => $remark,
                'status'            => 1,
            );
        }
        $model_coin->add($model_data);  //添加模特麻豆币记录
        
        //平台麻豆币添加<利润分成>
        if($type % 2 == 0){ //去除模特交押金的
            $last_platform_record = $model_coin->where(array('uid' => 0))->order(array('id' => 'desc'))->find();
            if(! empty($last_platform_record)){
                $platform_data = array(
                    'uid'               => 0,
                    'user_type'         => 2,
                    'trade_type'        => $type,
                    'trade_id'          => $trade_id,
                    'trust_coin'        => $last_platform_record['trust_coin'] + $platform_income,
                    'available_coin'    => $last_platform_record['available_coin'],
                    'current_trade_coin'=> $platform_income,
                    'after_trade_coin'  => $last_platform_record['after_trade_coin'] + $platform_income,
                    'type'              => 0,
                    'remark'            => $remark. ' 平台收益',
                    'status'            => 1,
                );
            }else{
                $platform_data = array(
                    'uid'               => 0,
                    'user_type'         => 2,
                    'trade_type'        => $type,
                    'trade_id'          => $trade_id,
                    'trust_coin'        => $platform_income,
                    'available_coin'    => 0,
                    'current_trade_coin'=> $platform_income,
                    'after_trade_coin'  => $platform_income,
                    'type'              => 0,
                    'remark'            => $remark. ' 平台收益',
                    'status'            => 1,
                );
            }
            $model_coin->add($platform_data);
        }
    }
    
    /**
     * 模特申请提现
     * @param type $uid             模特id
     * @param type $alipay_account  模特支付宝账户
     * @param type $cash            模特提现金额
     */
    public function withdraw($uid=0, $alipay_account='', $cash=''){
        $model_coin = M('Model_coin')->where(array('uid' => $uid, 'status' => 1))->order(array('id' => 'desc'))->find();
        if(!empty($model_coin)){
            $avaliable_coin = $model_coin['after_trade_coin'] - $model_coin['trust_coin'];
            if($alipay_account >= $cash){
                $user = M('User')->field('username')->find($uid);
                $withdraw = array(
                    'uid'            => $uid,
                    'username'       => $user['username'],
                    'alipay_account' => $alipay_account,
                    'cash'           => $cash,
                    'manage_status'  => 1,
                    'status'         => 1,
                );
                M('Withdraw')->add($withdraw);
                $data = array(
                    'code' => 1,
                    'msg'  => '申请提现成功，在1-2个工作日内到账',
                );
            }else{
                $data = array(
                    'code'  => 0,
                    'msg'   => '抱歉，您的可提现金额不足，不能提现，当前可天线金额为'.$avaliable_coin,
                );
            }
            $this->ajaxReturn($data);
        }
        $this->ajaxReturn(array(
            'code'  => 0,
            'msg'   => '抱歉，你还未有交易'
        ));
    }
}